const { MaterialOrder, Material, Payment, User } = require('../models');
const { generateOrderNumber } = require('../utils/payment');
const { generateTokenWithExpiry, isTokenValid } = require('../utils/token');
const { sendOrderConfirmationEmail } = require('../utils/mailer');
const { sequelize } = require('../config/database');

/**
 * 创建材料订单
 */
exports.createOrder = async (req, res) => {
  const transaction = await sequelize.transaction();
  
  try {
    const { materialId, customerName, customerEmail, customerPhone, notes } = req.body;
    
    // 获取用户ID（如果已登录）
    const userId = req.user ? req.user.id : null;
    
    // 查找材料信息
    const material = await Material.findByPk(materialId);
    if (!material) {
      await transaction.rollback();
      return res.status(404).json({ message: '材料不存在' });
    }
    
    // 检查材料是否已审核
    if (!material.isApproved) {
      await transaction.rollback();
      return res.status(400).json({ message: '该材料尚未通过审核，暂不可购买' });
    }
    
    // 生成订单号
    const orderNumber = generateOrderNumber('MAT');
    
    // 创建订单
    const order = await MaterialOrder.create({
      orderNumber,
      userId,
      materialId,
      customerName,
      customerEmail,
      customerPhone,
      amount: material.price,
      status: 'pending',
      ipAddress: req.ip,
      notes
    }, { transaction });
    
    // 提交事务
    await transaction.commit();
    
    // 发送订单确认邮件
    try {
      await sendOrderConfirmationEmail(customerEmail, {
        orderNumber,
        customerName,
        materialTitle: material.title,
        amount: material.price
      });
    } catch (emailError) {
      console.error('发送订单确认邮件失败:', emailError);
      // 邮件发送失败不影响订单创建
    }
    
    res.status(201).json({
      message: '订单创建成功',
      order: {
        orderNumber: order.orderNumber,
        status: order.status,
        amount: order.amount
      }
    });
  } catch (error) {
    await transaction.rollback();
    console.error('创建订单失败:', error);
    res.status(500).json({ message: '创建订单失败', error: error.message });
  }
};

/**
 * 获取订单详情
 */
exports.getOrderDetails = async (req, res) => {
  try {
    const { orderNumber } = req.params;
    
    const order = await MaterialOrder.findOne({
      where: { orderNumber },
      include: [
        {
          model: Material,
          as: 'material',
          attributes: ['id', 'title', 'description', 'thumbnailPath']
        },
        {
          model: Payment,
          as: 'payment',
          attributes: ['id', 'status', 'paymentMethod', 'createdAt']
        }
      ]
    });
    
    if (!order) {
      return res.status(404).json({ message: '订单不存在' });
    }
    
    // 检查是否是订单所有者或管理员
    const isOwner = req.user && (req.user.id === order.userId || req.user.role === 'admin');
    
    // 如果不是所有者，只返回基本信息
    if (!isOwner) {
      return res.status(200).json({
        orderNumber: order.orderNumber,
        status: order.status,
        material: {
          title: order.material.title,
          thumbnailPath: order.material.thumbnailPath
        },
        createdAt: order.createdAt
      });
    }
    
    // 返回完整订单信息
    res.status(200).json({
      id: order.id,
      orderNumber: order.orderNumber,
      customerName: order.customerName,
      customerEmail: order.customerEmail,
      customerPhone: order.customerPhone,
      amount: order.amount,
      status: order.status,
      notes: order.notes,
      downloadToken: order.downloadToken,
      downloadTokenExpiry: order.downloadTokenExpiry,
      downloadCount: order.downloadCount,
      maxDownloads: order.maxDownloads,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt,
      material: order.material,
      payment: order.payment
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({ message: '获取订单详情失败', error: error.message });
  }
};

/**
 * 生成下载令牌
 */
exports.generateDownloadToken = async (req, res) => {
  try {
    const { orderNumber } = req.params;
    const { expiryHours } = req.body;
    
    // 查找订单
    const order = await MaterialOrder.findOne({
      where: { orderNumber },
      include: [
        {
          model: Payment,
          as: 'payment'
        }
      ]
    });
    
    if (!order) {
      return res.status(404).json({ message: '订单不存在' });
    }
    
    // 检查订单状态
    if (order.status !== 'completed') {
      return res.status(400).json({ message: '订单尚未完成，无法生成下载令牌' });
    }
    
    // 检查支付状态
    if (!order.payment || order.payment.status !== 'success') {
      return res.status(400).json({ message: '订单尚未支付，无法生成下载令牌' });
    }
    
    // 生成下载令牌
    const { token, expiry } = generateTokenWithExpiry(expiryHours || 24);
    
    // 更新订单
    await order.update({
      downloadToken: token,
      downloadTokenExpiry: expiry
    });
    
    res.status(200).json({
      message: '下载令牌生成成功',
      token,
      expiry
    });
  } catch (error) {
    console.error('生成下载令牌失败:', error);
    res.status(500).json({ message: '生成下载令牌失败', error: error.message });
  }
};

/**
 * 验证下载令牌
 */
exports.verifyDownloadToken = async (req, res) => {
  try {
    const { orderNumber, token } = req.params;
    
    // 查找订单
    const order = await MaterialOrder.findOne({
      where: { orderNumber },
      include: [
        {
          model: Material,
          as: 'material',
          attributes: ['id', 'title', 'filePath', 'noWatermarkFilePath']
        }
      ]
    });
    
    if (!order) {
      return res.status(404).json({ message: '订单不存在' });
    }
    
    // 验证令牌
    if (order.downloadToken !== token) {
      return res.status(401).json({ message: '下载令牌无效' });
    }
    
    // 验证令牌是否过期
    if (!isTokenValid(order.downloadTokenExpiry)) {
      return res.status(401).json({ message: '下载令牌已过期' });
    }
    
    // 验证下载次数
    if (order.downloadCount >= order.maxDownloads) {
      return res.status(400).json({ message: '已达到最大下载次数' });
    }
    
    // 增加下载次数
    await order.update({
      downloadCount: order.downloadCount + 1
    });
    
    // 返回文件路径
    res.status(200).json({
      message: '令牌验证成功',
      materialId: order.material.id,
      materialTitle: order.material.title,
      filePath: order.material.filePath,
      noWatermarkFilePath: order.material.noWatermarkFilePath,
      downloadCount: order.downloadCount + 1,
      maxDownloads: order.maxDownloads
    });
  } catch (error) {
    console.error('验证下载令牌失败:', error);
    res.status(500).json({ message: '验证下载令牌失败', error: error.message });
  }
};

/**
 * 获取用户的订单列表
 */
exports.getUserOrders = async (req, res) => {
  try {
    const userId = req.user.id;
    
    const orders = await MaterialOrder.findAll({
      where: { userId },
      include: [
        {
          model: Material,
          as: 'material',
          attributes: ['id', 'title', 'thumbnailPath']
        },
        {
          model: Payment,
          as: 'payment',
          attributes: ['id', 'status', 'paymentMethod', 'createdAt']
        }
      ],
      order: [['createdAt', 'DESC']]
    });
    
    res.status(200).json(orders);
  } catch (error) {
    console.error('获取用户订单列表失败:', error);
    res.status(500).json({ message: '获取用户订单列表失败', error: error.message });
  }
};

/**
 * 更新订单状态
 */
exports.updateOrderStatus = async (req, res) => {
  try {
    const { orderNumber } = req.params;
    const { status } = req.body;
    
    // 检查用户权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '没有权限执行此操作' });
    }
    
    // 查找订单
    const order = await MaterialOrder.findOne({
      where: { orderNumber }
    });
    
    if (!order) {
      return res.status(404).json({ message: '订单不存在' });
    }
    
    // 更新状态
    await order.update({ status });
    
    res.status(200).json({
      message: '订单状态更新成功',
      orderNumber,
      status
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({ message: '更新订单状态失败', error: error.message });
  }
};